import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import {getToken, setToken} from '@/utils/auth'
import router from "@/router";
import de from "element-ui/src/locale/lang/de";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 600000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      config.headers['authorization'] = getToken()
      config.headers['ip'] = sessionStorage.getItem("ip")
    }
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    if(response.headers['authorization']!=undefined){
        setToken(response.headers['authorization'])

    }
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 0) {
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    if (error.response.status==401){
        return Promise.reject({code:401,data:null,msg:"暂无权限"})
    }else {
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
  }
)

export default service
